<template>
	<view class="home" :style="bgStyle">
		<!-- 自定义导航栏 -->
		<custom-navbar title="高新园虚拟园区" :transparent="true" :show-back="true" @back="handleBack" />

		<view class="content p4030 pb150" :style="{ paddingTop: navBarHeight + 'px' }">
			<!-- 聊天内容区域 -->
			<view class="mt20 w100">
				<!-- 聊天记录 -->
				<view class="chat-container">
					<view v-for="(item, index) in chatList" :key="index" class="chat-item" :class="item.type">
						<view v-if="item.type === 'bot'" class="chat-bubble bot">
							<view class="f34bc0 mb8">{{ item.content }}</view>
							<view v-if="item.subContent" class="f26bc7A8FB2">{{ item.subContent }}</view>
						</view>
						<view v-else class="chat-bubble user">
							<view class="f34bc0">{{ item.content }}</view>
						</view>
					</view>
					<view v-if="isLoading" class="chat-item bot">
						<view class="chat-bubble bot">
							<view class="f34bc0 mb8">正在思考中...</view>
						</view>
					</view>
				</view>

				<view class="issue" v-if="chatList.length <= 1">
					<image mode="widthFix" class="bg-image" :src="cdn('人物.svg')"></image>
					<view class="p40 fccend w100 content-overlay">
						<view class="f34bc0 mb8">Hi~ 我是智能客服 小新</view>
						<view class="f26bc7A8FB2">欢迎向我提问，我会努力为您解答！</view>
					</view>
					<view class="problem content-overlay p2030">
						<view class="fce right mb48">
							<view class="tilte fcc" style="margin-right: 190rpx;">
								<image class="tiltes" src="/static/images/service/猜您想问.svg"></image>
								<image class="tliteimg" src="/static/images/home/波浪.svg"></image>
							</view>
							<view>
								<up-button text="换一批" @click="refreshQuestions"
									style="width: 120rpx;height: 50rpx;border-radius: 500rpx 500rpx 500rpx 500rpx;"
									color="linear-gradient( 90deg, #398DFB 0%, #61DBFF 100%)"></up-button>
							</view>
						</view>
						<view v-for="(item,index) in questionList" :key="item.question_id">
							<view class="fcsb" @click="sendQuestion(item)">
								<view class="fc">
									<image class="wh34" src="/static/images/service/热门.svg"></image>
									<view class="ml30 f26bc3">{{ item.question_title }}</view>
								</view>
								<image class="wh20 ml5" src="/static/images/home/Frame(2).svg"></image>
							</view>
							<up-line v-if="index < questionList.length - 1" margin="30rpx 0"></up-line>
						</view>
					</view>
				</view>
				<view class="w100 fcc" v-if="chatList.length > 1">
					<view class="f26bc7A8FB2">
						- 开启新对话 -
					</view>
				</view>
			</view>

			<!-- 固定在底部的发送区域 -->
			<view class="fixed-bottom">
				<!-- 快捷操作选项 -->
				<view class="send">
					<view class="sendtype fc">
						<view v-for="(item,index) in typelist" :key="index" class="fcc item"
							:style="{ marginRight: index < typelist.length - 1 ? '14rpx' : '0' }">
							<image class="wh40" :src='item.icon'></image>
							<view class="f245c3">{{item.lable}}</view>
						</view>
					</view>

					<!-- 消息输入框 -->
					<view class="message-input fc">
						<image class="voice-icon" src="/static/images/service/语音.svg"></image>
						<input class="input-box" v-model="inputMessage" placeholder="输入要说的内容吧" @confirm="sendMessage" />
						<up-button class="send-btn" text="发送" @click="sendMessage"
							color="linear-gradient(90deg, #398DFB 0%, #61DBFF 100%)"></up-button>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		computed,
		onMounted,
		getCurrentInstance
	} from 'vue'
	import {
		useUserStore
	} from '@/stores/user'
	import {
		useI18n
	} from 'vue-i18n'

	import CustomNavbar from '@/components/custom-navbar.vue'
	import {
		getaiquestion,
		getContent,
		ceshi
		// getAIResponse
	} from '@/api/service' // 假设新增了getAIResponse接口
	// 获取全局cdn方法
	const {
		proxy
	} = getCurrentInstance()
	const cdn = (path) => proxy.$cdn + path
	const {
		t
	} = useI18n()
	const userStore = useUserStore()
	const searchKey = ref('')

	// 获取系统信息
	const systemInfo = uni.getSystemInfoSync()
	const navBarHeight = computed(() => systemInfo.statusBarHeight + 44)
	const bgStyle = ref({})

	// 问题列表
	const questionList = ref([])
	// 对话列表
	const chatList = ref([])
	// 输入的消息
	const inputMessage = ref('')
	// 是否正在加载
	const isLoading = ref(false)

	// 初始化
	onMounted(() => {
		bgStyle.value = {
			backgroundImage: `url(https://gx.jifgou.com/image/homebg.png)`,
			backgroundSize: '100% auto',
			backgroundRepeat: 'no-repeat',
			minHeight: '100vh'
		}
		// 获取热门问题
		fetchHotQuestions()
	})

	// 获取热门问题
	const fetchHotQuestions = async () => {
		try {
			const res = await getaiquestion()
			if (res.code === 200) {
				questionList.value = res.data.data.slice(0, 3) // 只取前三个问题
			}
		} catch (error) {
			console.error('获取热门问题失败:', error)
		}
	}

	// 换一批问题
	const refreshQuestions = async () => {
		await fetchHotQuestions()
	}
	const defaultReplies = [
		"我已收到您的问题，正在为您查询相关信息。",
		"这个问题很有趣，让我为您详细解答。",
		"感谢您的提问，以下是相关信息：",
		"我正在处理您的请求，请稍等片刻。"
	]
	// 发送热门问题（直接使用问题ID）
	const sendQuestion = async (question) => {
		if (isLoading.value) return

		// 添加用户消息到聊天列表
		chatList.value.push({
			type: 'user',
			content: question.question_title
		})

		isLoading.value = true

		try {
			// 调用固定回复的getContent接口
			const res = await getContent({
				lang_code: 'zh',
				question_id: question.question_id
			})

			if (res.code === 200) {
				let replyContent = res.data?.data?.question_content ||
					res.data?.content ||
					'抱歉，我暂时无法回答这个问题。'

				chatList.value.push({
					type: 'bot',
					content: replyContent
				})
			} else {
				console.error('API返回异常状态:', res)
				chatList.value.push({
					type: 'bot',
					content: `服务暂时不可用，错误代码: ${res.code}`
				})
			}
		} catch (error) {
			console.error('发送消息失败:', error)
			chatList.value.push({
				type: 'bot',
				content: '网络连接出现问题，请检查您的网络后重试。'
			})
		} finally {
			isLoading.value = false
			scrollToBottom()
		}
	}


	// 发送用户输入的消息（使用AI接口）
	const sendMessage = async () => {
		if (!inputMessage.value.trim() || isLoading.value) return

		// 添加用户消息到聊天列表
		chatList.value.push({
			type: 'user',
			content: inputMessage.value
		})

		const tempMessage = inputMessage.value
		inputMessage.value = ''
		isLoading.value = true

		try {
			// 调用AI自由回答的ceshi接口
			const res = await ceshi({
				question: tempMessage
			})

			if (res.code === 200) {
				let replyContent = res.data?.data?.content ||
					'抱歉，我暂时无法回答这个问题。'

				chatList.value.push({
					type: 'bot',
					content: replyContent
				})
			} else {
				console.error('API返回异常状态:', res)
				chatList.value.push({
					type: 'bot',
					content: `服务暂时不可用，错误代码: ${res.code}`
				})
			}
		} catch (error) {
			console.error('发送消息失败:', error)
			chatList.value.push({
				type: 'bot',
				content: '网络连接出现问题，请检查您的网络后重试。'
			})
		} finally {
			isLoading.value = false
			scrollToBottom()
		}
	}
	// 滚动到底部
	const scrollToBottom = () => {
		setTimeout(() => {
			uni.pageScrollTo({
				scrollTop: 99999,
				duration: 300
			})
		}, 100)
	}
	// 快捷操作选项列表
	const typelist = ref([{
			icon: '/static/images/service/园区向导.svg',
			lable: '园区向导'
		},
		{
			icon: '/static/images/service/预约考察.svg',
			lable: '预约考察'
		},
		{
			icon: '/static/images/service/活动报名.svg',
			lable: '活动报名'
		},
		{
			icon: '/static/images/service/人工客服.svg',
			lable: '人工客服'
		}
	])

	// 返回按钮处理
	const handleBack = () => {
		uni.switchTab({
			url: '/pages/index/index'
		});
	};

	// 选择热门问题
	const selectQuestion = (question) => {
		inputMessage.value = question.question_title
	}
</script>

<style lang="scss" scoped>
	.home {
		width: 100%;
		min-height: 100vh;
		position: relative;

		.content {
			padding-top: var(--status-bar-height);
			padding-top: calc(var(--status-bar-height) + 44px);
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			padding-bottom: 200rpx;
			/* 为底部固定区域留出空间 */

			.chat-container {
				width: 100%;
				// padding: 20rpx 30rpx;

				.chat-item {
					margin-bottom: 30rpx;

					&.bot {
						display: flex;
						justify-content: flex-start;
					}

					&.user {
						display: flex;
						justify-content: flex-end;
					}

					.chat-bubble {
						max-width: 80%;
						padding: 20rpx 30rpx;
						border-radius: 16rpx;

						&.bot {
							background-color: #f5f5f5;
						}

						&.user {
							background: linear-gradient(90deg, #398DFB 0%, #61DBFF 100%);
							color: white;
						}
					}
				}
			}

			.issue {
				width: 100%;
				height: 540rpx;
				position: relative;
				overflow: hidden;

				.bg-image {
					width: 105%;
					height: auto;
					position: absolute;
					left: 50%;
					top: 50%;
					transform: translate(-50%, -50%);
					z-index: 0;
				}

				.content-overlay {
					position: relative;
					z-index: 1;
				}

				.problem {
					width: 100%;
					height: 360rpx;
					// background-color: white;
					border-radius: 20rpx;
					box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);

					.right {
						width: 100%;

						.tilte {
							position: relative;

							.tiltes {
								width: 120rpx;
								height: 38rpx;
							}

							.tliteimg {
								width: 75rpx;
								height: 15.37rpx;
								position: absolute;
								bottom: -8rpx;
							}
						}
					}
				}
			}
		}

		/* 固定在底部的发送区域样式 */
		.fixed-bottom {
			position: fixed;
			bottom: 0;
			left: 0;
			right: 0;
			background: #fff;
			padding: 20rpx 30rpx;
			box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);

			.send {
				.sendtype {
					display: flex;
					justify-content: space-between;
					margin-bottom: 20rpx;

					.item {
						flex: 1;
						height: 66rpx;
						background: #ffffff;
						border-radius: 500rpx;
						border: 2rpx solid #f5f5f5;
						margin-right: 14rpx;

						&:last-child {
							margin-right: 0;
						}
					}
				}

				/* 消息输入框样式 */
				.message-input {
					display: flex;
					align-items: center;
					background: #f5f5f5;
					border-radius: 50rpx;
					padding: 10rpx 20rpx;

					.voice-icon {
						width: 40rpx;
						height: 40rpx;
						margin-right: 20rpx;
					}

					.input-box {
						flex: 1;
						height: 60rpx;
						font-size: 26rpx;
						color: #333;
						background: transparent;
					}

					.send-btn {
						width: 120rpx;
						height: 60rpx;
						margin-left: 20rpx;
						border-radius: 50rpx;
						font-size: 28rpx;
					}
				}
			}
		}
	}
</style>